<template>
  <div class="app-container" style="position: relative">
    <div style="padding: 0 15px;" @click="showLeft=!showLeft" v-if="!showLeft">
      <svg
          :class="{'is-active':false}"
          class="hamburger"
          height="64"
          viewBox="0 0 1024 1024"
          width="64"
          xmlns="http://www.w3.org/2000/svg"
      >
        <path
            d="M408 442h480c4.4 0 8-3.6 8-8v-56c0-4.4-3.6-8-8-8H408c-4.4 0-8 3.6-8 8v56c0 4.4 3.6 8 8 8zm-8 204c0 4.4 3.6 8 8 8h480c4.4 0 8-3.6 8-8v-56c0-4.4-3.6-8-8-8H408c-4.4 0-8 3.6-8 8v56zm504-486H120c-4.4 0-8 3.6-8 8v56c0 4.4 3.6 8 8 8h784c4.4 0 8-3.6 8-8v-56c0-4.4-3.6-8-8-8zm0 632H120c-4.4 0-8 3.6-8 8v56c0 4.4 3.6 8 8 8h784c4.4 0 8-3.6 8-8v-56c0-4.4-3.6-8-8-8zM142.4 642.1L298.7 519a8.84 8.84 0 0 0 0-13.9L142.4 381.9c-5.8-4.6-14.4-.5-14.4 6.9v246.3a8.9 8.9 0 0 0 14.4 7z"/>
      </svg>
    </div>

    <el-row :gutter="10">
      <el-col :span="showLeft?4:0">
        <el-card class="box-card" style="position: relative">

          <el-tooltip class="item" effect="dark" content="隐藏" placement="left" >
            <div class="el-icon-circle-close"  @click="showLeft=!showLeft"
               style="position: absolute;right:10px;top:10px;font-size: 24px;width: 20px;height: 20px"></div>
          </el-tooltip>
          <el-tabs type="card" v-model="selectTab">
            <el-tab-pane style="overflow: auto;height: 80vh;" label="客户分类" name="first">
              <el-tree
                  ref="typeTree"
                  :data="typeList"
                  :props="defaultProps"
                  highlight-current
                  accordion
                  node-key="id"
                  @node-click="checkType">
              </el-tree>
            </el-tab-pane>
            <el-tab-pane  style="overflow: auto;height: 80vh;" label="销售区域" name="second">
              <el-tree
                  ref="areaTree"
                  :data="areaData"
                  highlight-current
                  :props="defaultProps"
                  node-key="id"
                  accordion
                  @node-click="checkArea">
              </el-tree>
            </el-tab-pane>
          </el-tabs>

        </el-card>
        <div id="closeBtn" @click="showLeft = !showLeft"></div>

      </el-col>
      <el-col :span="showLeft?18:24">
        <!--工具栏-->
        <div class="head-container">
          <div v-if="crud.props.searchToggle">
            <!-- 搜索 -->
            <el-form label-width="80px" size="small" v-formkey="{query:toQuery}">
              <el-row :gutter="10">
                <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
                  <el-form-item label="创建日期">
                    <div class="flex flex-row">
                      <el-date-picker
                        v-model="query.createStartTime"
                        align="right"
                        unlink-panels
                        class="fl1"
                        format="yyyy - MM - dd "
                        value-format="yyyy-MM-dd"
                        default-value
                        range-separator=""
                        placeholder="开始日期"
                      />
                      <el-date-picker
                        v-model="query.createEndTime"
                        align="right"
                        unlink-panels
                        class="fl1"
                        format="yyyy - MM - dd "
                        value-format="yyyy-MM-dd"
                        default-value
                        range-separator=""
                        placeholder="结束日期"
                      />
                    </div>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
                  <el-form-item label="关键字">
                    <el-input v-model="query.keyword" placeholder="输入关键字搜索"/>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
                  <el-form-item label="部门">
                    <treeselect
                        v-model="query.deptId"
                        :options="depts"
                        placeholder="选择部门"
                        style="width: 100%"
                        :normalizer="normalizer"
                    />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
                  <el-form-item label="客户业务员">
                    <zSelect :value.sync="query.userId" url="api/dropDown/sysUserList" :params="{businessAttr:'3'}"
                             style="width:  100%"/>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="10">
                <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
                  <el-form-item label="所属二批">
                    <zSelect :value.sync="query.sCustomerId" url="api/dropDown/basCustomerList" :params="{type:3}"
                             style="width:  100%;"/>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
                  <el-form-item label="是否有坐标">
                    <el-select v-model="query.location" clearable class="edit-input" placeholder="请选择" style="width: 100%;">
                      <el-option
                          v-for="(item,index) in dict.common_yes_or_no"
                          :key="index"
                          :label="item.label"
                          :value="item.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
                  <el-form-item label="状态">
                    <el-select v-model="query.status" class="edit-input" clearable placeholder="请选择" style="width: 100%;">
                      <el-option
                          v-for="(item,index) in dict.common_status"
                          :key="index"
                          :label="item.label"
                          :value="item.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
                  <el-form-item label="送货地址">
                    <el-input v-model="query.deliveryAddress" placeholder="输入送货地址搜索"/>
                  </el-form-item>
                </el-col>

              </el-row>

              <el-row :gutter="10">
                <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
                  <el-form-item label="商贸公司">
                    <zSelect  :value.sync="query.fCustomerId"  url="/api/dropDown/basCustomerList" :params="{type:2}"
                             style="width:  100%;"/>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
                  <el-form-item label="客户类型">
                    <el-select v-model="query.type" class="edit-input" clearable placeholder="请选择" style="width: 100%;">
                      <el-option
                        v-for="(item,index) in dict.t_bas_customer_type"
                        :key="index"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
                  <el-form-item label="是否直营">
                    <el-select v-model="query.isDirectSale" clearable>
                      <el-option
                        v-for="(item,index) in dict.common_yes_or_no"
                        :key="index"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </el-form-item>

                </el-col>
                <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
                  <el-form-item label="是否会员">
                    <el-select v-model="query.isVip" clearable>
                      <el-option
                        v-for="(item,index) in dict.common_yes_or_no"
                        :key="index"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </el-form-item>

                </el-col>
                <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
                  <el-form-item label="商品名称">
                    <table-select
                      :tableColumns="[{prop:'goodsCode',label:'商品编码',width:'100'},{prop:'goodsName',label:'商品名称',width: '280'}]"
                      labelKey="goodsName"
                      valueKey="goodsId"
                      :value.sync="query.customerGoodsId"
                      placeholder="请选择商品"
                      :multiple="false"
                      url="/api/dropDown/basGoodsListForAdd"
                    ></table-select>
                  </el-form-item>
                </el-col>
              </el-row>

            </el-form>
            <rrOperation :crud="crud"/>
          </div>

          <crudOperation :permission="permission">
            <el-button
                slot="left"
                v-permission="['admin', 'basCustomer:edit']"
                class="filter-item"
                size="mini"
                type="primary"
                @click="toAdd"
            >
              新增
            </el-button>
            <el-button
              slot="left"
              class="filter-item"
              size="mini"
              type="primary"
              @click="toSyncSCustomerGoods"
            >
              二批商品同步
            </el-button>
            <el-button
              slot="left"
              class="filter-item"
              size="mini"
              type="primary"
              @click="toSyncCustomerGoods"
            >
              客户商品同步
            </el-button>
            <el-button
              slot="left"
              class="filter-item"
              size="mini"
              type="primary"
              @click="syncFCustomerGoodsToSCustomerGoods"
            >
              商贸商品下发
            </el-button>
            <el-button
              slot="left"
              class="filter-item"
              size="mini"
              type="primary"
              @click="syncSCustomerGoodsToCustomerGoods"
            >
              二批商品下发
            </el-button>
<!--            <el-button-->
<!--              slot="right"-->
<!--              class="filter-item"-->
<!--              size="mini"-->
<!--              @click="showHistory(crud.selections[0])"-->
<!--            >-->
<!--              修改记录-->
<!--            </el-button>-->
            <el-button
              slot="left"
              class="filter-item"
              size="mini"
              type="primary"
              @click="createSysUser"
              :disabled="crud.selections.length < 1"
            >
              生成用户
            </el-button>
            <el-button
              slot="left"
              class="filter-item"
              size="mini"
              type="primary"
              @click="openBatchUpdate"
              :disabled="!crud.selections.length"
            >
              批量修改
            </el-button>
            <el-button slot="left"  class="filter-item"  size="mini"  type="success"  @click="importGoodsStatus = true" >导入商品</el-button>
          </crudOperation>
        </div>
        <j-dialog
          title="授信信息"
          is-mask
          style="width: 40%"
          :visible.sync="showCredit"
        >
          <el-descriptions class="margin-top"  :column="2" :size="size" border>
            <template slot="extra">
              <el-button type="primary" size="small" @click="passOrReject('PASS')">同意</el-button>
              <el-button type="primary" size="small" @click="passOrReject('REJECT')">驳回</el-button>
            </template>
            <el-descriptions-item>
              <template slot="label">
                <i class="el-icon-user"></i>
                客户名称
              </template>
              {{ creditData.customerName }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                <i class="el-icon-user"></i>
                联系人
              </template>
              {{ creditData.contactName }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                <i class="el-icon-mobile-phone"></i>
                联系电话
              </template>
              {{ creditData.contactPhone }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                <i class="el-icon-tickets"></i>
                身份证号
              </template>
              {{ creditData.cardNo }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                <i class="el-icon-tickets"></i>
                信用等级
              </template>
              {{ dict.label.t_bas_customer_credit_level[creditData.creditLevel] }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                <i class="el-icon-tickets"></i>
                信用额度
              </template>
              {{ creditData.creditLevel }}
            </el-descriptions-item>
            <el-descriptions-item >
              <template slot="label">
                <i class="el-icon-office-building"></i>
                送货地址
              </template>
              {{ creditData.deliveryAddress }}
            </el-descriptions-item>
          </el-descriptions>
          <div class="flex flex-row" style="width: 100%">
            <div class="fl1">
              <div class="flex j-content imgTitle" style="width: 100%">营业执照</div>
              <div class="flex j-content a-item">
                <el-image
                  style="width: 200px; height: 200px"
                  :src="creditData.stampImageUrl"
                  :preview-src-list="[creditData.stampImageUrl]">
                </el-image>
              </div>
            </div>
            <div class="fl1">
              <div class="flex j-content imgTitle" style="width: 100%">门店照片</div>
              <div class="flex j-content a-item">
                <el-image
                  style="width: 200px; height: 200px"
                  :src="creditData.imageUrl"
                  :preview-src-list="[creditData.imageUrl]">
                </el-image>
              </div>
            </div>
          </div>
        </j-dialog>
        <!--批量修改-->
        <j-dialog title="批量修改"
                  v-dialogDrag
                  :visible.sync="showBatchUpdateDialog"
                  style="width: 40vw"
        >
          <el-form :model="batchUpdate" label-width="100px" ref="batchUpdateForm">
            <el-form-item label="客户区域">
              <treeselect
                v-model="batchUpdate.customerAreaId"
                :options="areaData"
                placeholder="选择客户区域"
                style="width: 370px"
                :normalizer="normalizer"
              />
            </el-form-item>
<!--            <el-form-item label="结算方式">-->
<!--              <zSelect :value.sync="batchUpdate.settlementId" url="api/dropDown/basSettlementList" style="width:  370px;"/>-->
<!--            </el-form-item>-->
<!--            <el-form-item label="所属销售体系" prop="saleSystemId">-->
<!--              <zSelect :value.sync="batchUpdate.saleSystemId"  url="api/dropDown/basSaleSystemList" style="width:  370px;"/>-->
<!--            </el-form-item>-->
<!--            <el-form-item label="所属仓库" prop="warehouseId">-->
<!--              <zSelect :value.sync="batchUpdate.warehouseId" :showName="form.warehouseName" url="api/dropDown/basWarehouseList" style="width:  370px;"/>-->
<!--            </el-form-item>-->
            <el-form-item label="部门" prop="deptId">
              <treeselect
                v-model="batchUpdate.deptId"
                :options="depts"
                placeholder="选择部门"
                style="width:  370px"
                :normalizer="normalizer"
              />
            </el-form-item>
            <el-form-item label="业务员" prop="">
              <zSelect :value.sync="batchUpdate.userId"  url="api/dropDown/sysUserList" :params="{businessAttr:'3'}"
                       style="width:  370px;"/>
            </el-form-item>
            <el-form-item label="终端分类">
              <el-select v-model="batchUpdate.endCustomerType" class="edit-input" placeholder="请选择" style="width:  370px;">
                <el-option
                  v-for="(item,index) in dict.customer_type"
                  :key="index"
                  :label="item.label"
                  :value="(item.value).toString()"
                />
              </el-select>
            </el-form-item>
              <el-form-item label="拜访时间" prop="visitTime">
                <el-select multiple  v-model="batchUpdate.visitTime"  placeholder="请选择" style="width: 370px;">
                  <el-option
                    v-for="item in dateScopes"

                    :key="item.label"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            <el-form-item label="拜访线路">
              <zSelect :value.sync="batchUpdate.visitLineId"  url="api/dropDown/basLineList"
                       style="width:  370px;"/>
            </el-form-item>
<!--            <el-form-item label="客户属性" prop="customerAttr">-->
<!--              <el-select v-model="batchUpdate.customerAttr" class="edit-input" placeholder="请选择" style="width:  370px;">-->
<!--                <el-option-->
<!--                  v-for="(item,index) in dict.t_bas_customer_customer_attr"-->
<!--                  :key="index"-->
<!--                  :label="item.label"-->
<!--                  :value="parseInt(item.value)"-->
<!--                />-->
<!--              </el-select>-->
<!--            </el-form-item>-->
<!--            <el-form-item label="渠道类型">-->
<!--              <el-select v-model="form.channel" class="edit-input" placeholder="请选择" style="width:  370px;">-->
<!--                <el-option-->
<!--                  v-for="(item,index) in dict.customer_channel"-->
<!--                  :key="index"-->
<!--                  :label="item.label"-->
<!--                  :value="(item.value).toString()"-->
<!--                />-->
<!--              </el-select>-->
<!--            </el-form-item>-->
            <div class="flex" style="margin-top: 10px;justify-content: right">
              <el-button type="primary" @click="batchUpdateSubmit">确认</el-button>
            </div>
          </el-form>
        </j-dialog>
        <!--修改记录弹窗-->

        <j-dialog title="修改记录"
                  v-dialogDrag
                  v-show="showHistoryDialog"
                  :visible.sync="showHistoryDialog"
                  style="width: 80%"
        >
          <history :data="current" :historyDialog="showHistoryDialog" :customerId="crud.order.customerId" :showAddBatchDialog.sync="showHistoryDialog" @change="afterChangeGoods"></history>
        </j-dialog>
        <div class="body-container">

          <vue-context-menu :contextMenuData="contextMenuData"
                            @tableConfig="tableConfig"
                            @deletedata="deletedata"></vue-context-menu>
          <!-- 表格配置 -->
          <el-dialog title="表格配置"
                     :visible.sync="tableConfigShow"
                     width="60%">
            <j-table-column-config :columns.sync="crud.header" :headerInfo="headerInfo"  @tabSave="tabSave" @pit="pit" />
          </el-dialog>
          <!--表格渲染-->

          <el-table ref="table"  border
                    height="700"

                    @cell-dblclick="toDetail"
                    v-loading="crud.loading"
                    :data="crud.data"
                    size="small"
                    style="width: 100%;"
                    v-if="isShowTable"
                    @header-dragend="changeColWidth"
                    @contextmenu.native="showMenu"
                    @row-click="crud.selectRow"
                    :row-style="crud.rowClass"
                    :row-class-name="crud.tableRowClassName"
                    @selection-change="crud.selectionChangeHandler"
          >
            <el-table-column :render-header="crud.renderHeader" type="selection" width="60"/>
            <el-table-column :render-header="crud.renderHeader" type="index" width="60" label="序号" />
            <el-table-column
              v-if="item.visible"
              v-for="(item, index) in crud.header"
              :key="`col_${index}`"
              :prop="item.prop"
              :label="columnLabel(item)"
              :width="item.width + 'px'"
              :data-porp='item.prop'
              @contextmenu.native="showMenu"
              @header-dragend="changeColWidth"
            >
              <!-- 自定义渲染模版 -->
              <template slot-scope="scope">
                <!-- 当列key为 sort 时，渲染一个手柄icon -->
                <template v-if="item.prop =='sort'">
                  <div class="handle_move">
                    <i :class="scope.row['sort']" />
                  </div>
                </template>
                <template v-else>
                  <span v-if="item.type == 1" style="margin-left: 0px">{{scope.row[`${item.prop}`]}}</span>
                  <span v-else-if="item.type == 2" style="margin-left: 0px">{{ parseTime(scope.row[`${item.prop}`])}}</span>
                  <span v-else-if="item.type == 3" style="margin-left: 0px">{{ getDict(`this.dict.label.${item.dictionary}["${scope.row[item.prop]}"]`) }}</span>
                  <span v-else-if="item.type == 4" style="margin-left: 0px">
                    <span v-if="item.prop =='visitTime'"  >
                      {{ setVisitTime(scope.row.visitTime) }}
                    </span>
                </span>
                </template>
              </template>
            </el-table-column>
<!--            <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('name')" prop="name" label="名称" />-->
<!--            <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('code')" prop="code" label="编码"/>-->
<!--            <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('type')" prop="type" label="客户类型">-->
<!--              <template slot-scope="scope">-->
<!--                {{ dict.label.t_bas_customer_type[scope.row.type] }}-->
<!--              </template>-->
<!--            </el-table-column>-->
<!--            <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('sourceType')" prop="sourceType" label="来源类型">-->
<!--              <template slot-scope="scope">-->
<!--                {{ dict.label.t_bas_customer_source_type[scope.row.sourceType] }}-->
<!--              </template>-->
<!--            </el-table-column>-->
<!--            <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('isContact')" prop="isContact" label="是否往来">-->
<!--              <template slot-scope="scope">-->
<!--                {{ dict.label.t_bas_customer_is_contact[scope.row.isContact] }}-->
<!--              </template>-->
<!--            </el-table-column>-->
<!--            <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('customerAttr')" prop="customerAttr" label="客户属性">-->
<!--              <template slot-scope="scope">-->
<!--                {{ dict.label.t_bas_customer_customer_attr[scope.row.customerAttr] }}-->
<!--              </template>-->
<!--            </el-table-column>-->
<!--            <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('channelType')" prop="channelType" label="渠道类型">-->
<!--              <template slot-scope="scope">-->
<!--                {{ dict.label.t_bas_customer_channel_type[scope.row.channelType] }}-->
<!--              </template>-->
<!--            </el-table-column>-->
<!--            <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('helpSign')" prop="helpSign" label="助记符"/>-->
<!--            <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('shortName')" prop="shortName" label="简称"/>-->
<!--            <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('chainName')" prop="chainName" label="连锁名称"/>-->
<!--            <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('address')" prop="address" label="地址"/>-->
<!--            <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('shopNo')" prop="shopNo" label="店号"/>-->
<!--            <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('taxNo')" prop="taxNo" label="税号"/>-->
<!--            <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('pcustomerName')" prop="pcustomerName" label="所属总店名称"/>-->
<!--            <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('mcustomerName')" prop="mcustomerName" label="所属商场名称"/>-->
<!--            <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('warehouseName')" prop="warehouseName" label="所属仓库名称"/>-->
<!--            <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('saleSystemName')" prop="saleSystemName" label="所属销售体系名称"/>-->
<!--            <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('fcustomerName')" prop="fcustomerName" label="所属商贸公司名称"/>-->
<!--            <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('scustomerName')" prop="scustomerName" label="所属二批名称"/>-->
<!--            <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('bankAccount')" prop="bankAccount" label="银行账户"/>-->
<!--            <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('bankOpenName')" prop="bankOpenName" label="开户银行"/>-->
<!--            <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('bankAccountName')" prop="bankAccountName" label="开户名"/>-->
<!--            <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('contactName')" prop="contactName" label="联系人"/>-->
<!--            <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('contactPhone')" prop="contactPhone" label="联系人电话"/>-->
<!--            <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('customerAreaName')" prop="customerAreaName" label="客户区域名称"/>-->
<!--            <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('customerTypeName')" prop="customerTypeName" label="客户分类名称"/>-->
<!--            <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('deptName')" prop="deptName" label="部门名称"/>-->
<!--            <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('userName')" prop="userName" label="业务员名称"/>-->
<!--            <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('clerkName')" prop="clerkName" label="文员名称"/>-->
<!--            &lt;!&ndash;        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('uploadStatus')" prop="uploadStatus" label="上传状态" />&ndash;&gt;-->
<!--            <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('status')" label="状态" prop="status">-->
<!--              <template slot-scope="scope">-->
<!--                {{ dict.label.common_status[scope.row.status] }}-->
<!--              </template>-->
<!--            </el-table-column>-->
<!--            <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('remark')" prop="remark" label="备注"/>-->
            <el-table-column :render-header="crud.renderHeader" v-permission="['admin','basCustomer:edit','basCustomer:del']" label="操作" fixed="right"
                             width="150px"
                             align="center">
              <template slot-scope="scope">
                <el-tooltip  v-permission="permission.credit" class="item" content="授信信息"  effect="light" placement="top">
                  <i v-if="scope.row.isNotice" class="el-icon-notebook-2 credit" @click="seeCredit(scope.row.id)"></i>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
          <!--分页组件-->
          <pagination layout='prev, pager, next, sizes,total'/>
          <el-dialog
            title='导入关联商品'
            :visible.sync="importGoodsStatus"
            width="400px"
          >
            <el-upload
              ref="upload_import"
              action="/api/basCustomer/importBasCustomerGoods"
              :auto-upload="false"
              :before-upload="beforeUpload"
              :headers="upload.headers"
              :limit="1"
              :on-error="handleError"
              :on-success="handleSuccess"
              accept=".xlsx, .xls"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
            <div class="tpl">
              <el-button
                size="small"
                type="info"
                @click="downloadTemplate('客户关联商品.xlsx')"
              >下载模板
              </el-button>
              <span class="tips">提示：仅允许导入.xls或.xlsx格式文件</span>
            </div>
            <div slot="footer" class="dialog-footer">
              <el-button type="text" @click="importStatus=false">取消</el-button>
              <el-button

                type="primary"
                @click="handleSubmit"
              >确认
              </el-button>
            </div>
          </el-dialog>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import crudBasCustomer, { batchUpdate } from '@/api/erp/basCustomer'
import CRUD, {crud, form, header, presenter} from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import history from "../../customer/basCustomer/history";
import {getDepts} from "@/api/system/dept";
import {getAreaTree} from "@/api/erp/basCustomerArea";
import {getCustomerTypeTree} from "@/api/erp/basCustomerType";
import { getToken } from "@/utils/auth";
import { publicListKey } from "@/utils/key";
import {getHeaderProperties} from "@/api/erp/headerProperties";
import {tablemixins} from "@/mixins/tablemixins";
import  jTableColumnConfig  from "@/components/jTableColumnConfig/jTableColumnConfig";
import request from '@/utils/request'
import { getBasCustomerCredit, passOrReject } from '@/api/erp/basCustomer'
import JDialog from '../../../../components/jDialog/jDialog'
import Treeselect from '@riophae/vue-treeselect'
import {deptJuniorUserList} from "@/api/erp/salesOrder";
// crud交由presenter持有
const defaultCrud = CRUD({
  title: '客户档案', url: 'api/basCustomer', sort: 'isNotice desc | code asc', crudMethod: {...crudBasCustomer}, optShow: {
    add: false,
    edit: false,
    del: true,
    download: true,
    leadingIn: true,
    enable: true,
    disable: true
  },
  queryOnPresenterCreated:false
})
const defaultForm = {
  id: null,
  code: null,
  name: null,
  type: null,
  sourceType: null,
  isContact: null,
  isLast: null,
  customerAttr: null,
  channelType: null,
  helpSign: null,
  spell: null,
  shortName: null,
  chainName: null,
  address: null,
  shopNo: null,
  taxNo: null,
  businessLicense: null,
  depositAmount: null,
  pcustomerId: null,
  pcustomerCode: null,
  pcustomerName: null,
  mcustomerId: null,
  mcustomerCode: null,
  mcustomerName: null,
  warehouseId: null,
  warehouseCode: null,
  warehouseName: null,
  saleSystemId: null,
  saleSystemCode: null,
  saleSystemName: null,
  fcustomerId: null,
  fcustomerCode: null,
  fcustomerName: null,
  sCustomerId: null,
  scustomerCode: null,
  scustomerName: null,
  bankId: null,
  bankAccount: null,
  bankOpenName: null,
  contactName: null,
  contactPhone: null,
  customerAreaId: null,
  customerAreaCode: null,
  customerAreaName: null,
  customerTypeId: null,
  customerTypeCode: null,
  customerTypeName: null,
  deptId: null,
  deptCode: null,
  deptName: null,
  userId: null,
  userCode: null,
  userName: null,
  payeeId: null,
  payeeCode: null,
  payeeName: null,
  clerkId: null,
  clerkCode: null,
  clerkName: null,
  settlementId: null,
  settlementCode: null,
  settlementName: null,
  settlebillType: null,
  balance: null,
  creditLimit: null,
  creditLevel: null,
  lng: null,
  lat: null,
  location: null,
  letterhead: null,
  imageUrl: null,
  stampImageUrl: null,
  fileUrl: null,
  uploadStatus: null,
  seq: null,
  status: null,
  remark: null,
  createUserId: null,
  createUserCode: null,
  createUserName: null,
  createTime: null,
  updateUserId: null,
  updateUserCode: null,
  updateUserName: null,
  updateTime: null,
  isDirectSale: null
}
export default {
  name: 'BasCustomer',
  components: { history, JDialog, pagination, crudOperation, rrOperation, udOperation, Treeselect,jTableColumnConfig},
  mixins: [presenter(defaultCrud), header(), form(defaultForm), crud(),publicListKey,tablemixins],
  dicts: ['t_bas_customer_credit_level', 'common_status', 't_bas_customer_type','customer_type',
    't_bas_customer_channel_type', 't_bas_customer_is_contact', 't_bas_customer_customer_attr', 't_bas_customer_source_type', 't_bas_customer_settlebill_type', 'common_yes_or_no'],
  data() {
    return {
      permission: {
        add: ['a'],
        edit: ['a'],
        del: ['admin', 'basCustomer:del'],
        import: ['admin', 'basCustomer:import'],
        export: ['admin', 'basCustomer:export'],
        copy: ['admin', 'basCustomer:copy'],
        upload: ['admin', 'basCustomer:upload'],
        download: ['admin', 'basCustomer:download'],
        enable: ['admin', 'basCustomer:enable'],
        disable: ['admin', 'basCustomer:disable'],
        credit: ['admin', 'basCustomer:credit'],
        history: ['admin', 'basCustomer:history'],
      },
      dateScopes: [{//周选择
        label: '周一', value: 1
      }, {
        label: '周二', value: 2
      }, {
        label: '周三', value: 3
      }, {
        label: '周四', value: 4
      }, {
        label: '周五', value: 5
      }, {
        label: '周六', value: 6
      }, {
        label: '周日', value: 7
      }],
      showCredit: false,
      rules: {
        code: [
          {required: true, message: '编码不能为空', trigger: 'blur'}
        ],
        name: [
          {required: true, message: '名称不能为空', trigger: 'blur'}
        ],
        isLast: [
          {required: true, message: '是否未级不能为空', trigger: 'blur'}
        ],
        customerAttr: [
          {required: true, message: '客户属性不能为空', trigger: 'blur'}
        ],
        customerAreaId: [
          {required: true, message: '客户区域id不能为空', trigger: 'blur'}
        ],
        customerTypeId: [
          {required: true, message: '客户分类id不能为空', trigger: 'blur'}
        ],
        deptId: [
          {required: true, message: '部门id不能为空', trigger: 'blur'}
        ],
        userId: [
          {required: true, message: '业务员不能为空', trigger: 'blur'}
        ],
        payeeId: [
          {required: true, message: '结算人不能为空', trigger: 'blur'}
        ],
        settlementId: [
          {required: true, message: '结算方式id不能为空', trigger: 'blur'}
        ]
      },
      queryTypeOptions: [
        {key: 'type', display_name: '客户类型'}
      ],
      typeList: [],
      depts: [],
      importGoodsStatus: false,
      areaData: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      is103:false,
      upload: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: getToken() },
        // 上传的地址
        url:'',
        // 上传的文件列表
        fileList: [],
        fileList1: [],
        // 公章图片列表
        stampImgList:[],
        // 门店图片列表
        imageList: []
      },
      selectTab: 'first',//选中的tab
      showLeft: true,
      headerInfo:{
        path:'api/basCustomer',
        name: 'basCustomer'
      },
      showBatchUpdateDialog:false,
      batchUpdate:{
        customerAreaId:null,
        deptId:null,
        userId:null,
        visitTime:[],
        visitLineId:null
      },
      creditData:{},
      showHistoryDialog: false,
      current:null,
      areaList:[],
      visitTimeList:['周一','周二','周三','周四','周五','周六','周日',],
      user: {},
      deptUserIds:''
    }
  },

  watch: {
    query: {
      handler: val => {
        this.$refs.typeTree.setCurrentKey(null)
        this.$refs.areaTree.setCurrentKey(null);
      },
      deep: true
    },
  },
  created() {
    this.getDepts()
    this.getTypeList()
    this.getAreaTree()
    this.is103 = window.location.href.includes('bw103')
    if(this.is103){
      //获取角色
      this.user = this.$store.state.user.user
      console.log(this.user)
      if(this.user.postName === '业务经理'){
        deptJuniorUserList({containsSelf: 1,businessAttr: 3,deptId:this.user.deptId}).then(res => {
          this.deptUserIds = res.content.map(item => item.id).join(',')
          this.crud.refresh()
        })
      }else{
        this.crud.refresh()
      }
    }else{
      this.crud.refresh()
    }
  },
  methods: {
    afterChangeGoods(goods) {
      this.showAddBatchDialog = false
      //去重，已经去重
      let arr = this.detailList.map(detail=>detail.goodsId)
      let _goods = []
      let result = []
      goods.forEach(good => {
        // if(!arr.includes(goods.goodsId)){
        good.isSelected = true
        this.crud.data.push(good)
        // }
      })
      // this.calcuForm()
    },

    showHistory(row) {
      this.showHistoryDialog = true
      this.current = row
    },
    // 获取数据前设置好接口地址
    [CRUD.HOOK.beforeRefresh]() {
      // const query = this.query
      // if (query.type && query.value) {
      //   this.crud.params[query.type] = query.value
      // } else {
      //   delete this.crud.params.type
      // })
      if(this.is103){
        if(this.user.postName === '业务代表'){
          //业务代表只能看到自己的
          // this.crud.query.userId = this.user.userId
        }else if(this.user.postName === '业务经理'){
          //业务经理只能看到自己部门的
          // this.crud.query.deptId = this.user.deptId
          this.crud.query.userIds = this.deptUserIds
        }
      }
      return true
    }, // 新增与编辑前做的操作
    [CRUD.HOOK.afterRefresh](crud, form) {
    },
    openBatchUpdate(){
      this.showBatchUpdateDialog = true
    },
    setVisitTime(val){
      if(!val)return
      return JSON.parse(val).map(i=>this.visitTimeList[~~i]).join(',')
    },
    getTypeList() {
      getCustomerTypeTree({page: 0, size: 999}).then(res => {
        this.typeList = res
      })
    },
    seeCredit(id){
      this.getCredit(id)
    },
    getAreaTree() {
      getAreaTree({status: 1}).then(res => {
        this.areaData = res
      })
    },
    async getCredit(id){
      const res = await getBasCustomerCredit({customerId:id})
      this.creditData = res.data.content[0]
      this.creditData.imageUrl = JSON.parse(this.creditData.imageUrl)[0].path
      this.creditData.stampImageUrl = JSON.parse(this.creditData.stampImageUrl)[0].path
      this.showCredit = true
    },
    normalizer(node) {
      //去掉children=[]的children属性
      if (node.children == null || node.children.length == 0) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      }
    },
    [CRUD.HOOK.afterToCU](crud, form) {
    },
    toDetail(row) {
      this.$router.push({
            path: 'basCustomerDetail/' + row.id,
            query: {id: row.id},
            meta: {title: '商品档案详情'}
          }
      )
    },
    // 获取弹窗内部门数据
    getDepts() {
      getDepts({status: 1}).then(res => {
        this.depts = res
      })
    },
    beforeUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 100
      if (!isLt2M) {
        this.$message.error('上传文件大小不能超过 100MB!')
      }
      return isLt2M
    },
    handleError(err, file, fileList) {
      this.crud.notify(
        ' -_- !~~ 服务器开小差了，稍后重试',
        CRUD.NOTIFICATION_TYPE.WARNING
      )
    },
    async passOrReject(type){
      const res = await passOrReject({type,id:this.creditData.id})
      if (res.status === 200){
        this.creditData = {}
        this.showCredit = false
        this.$message.success(res.msg)
        this.crud.refresh()
      }else {
        this.$message.error(res.msg)
      }
    },
    handleSuccess(response, file, fileList) {
      console.log('handleSuccess', response)
      if (response !== '导入成功') {
        const a = document.createElement('a')
        a.setAttribute('href', response.data.result)
        a.click()
      } else {
        this.crud.notify(response, CRUD.NOTIFICATION_TYPE.SUCCESS)
        this.$refs.upload.clearFiles()
        this.uploadDialgShow = false
        this.crud.refresh()
      }
    },

    toSyncSCustomerGoods(){
      let ids = []
      const that = this
      if (this.crud.selections.length){
        for (let i in this.crud.selections){
          ids.push(this.crud.selections[i].id)
        }
        crudBasCustomer.syncSCustomerGoods({ids}).then(res=>{
          if (res.status === 200){
            this.$message.success(res.msg)
          }else {
            this.$message.error(res.msg)
          }
          that.crud.loadingClose()
        }).catch(err=>{
          that.crud.loadingClose()
        })
        return
      }
      this.$confirm('未选择客户将同步所有客户会导致系统卡顿是否同步', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(res => {
        that.crud.loadingOpen()
        crudBasCustomer.syncSCustomerGoods({ids}).then(res=>{
          if (res.status === 200){
            this.$message.success(res.msg)
          }else {
            this.$message.error(res.msg)
          }
          that.crud.loadingClose()
        }).catch(err=>{
          that.crud.loadingClose()
        })
      }).catch(() => {
      })
    },
    handleSubmit() {
      // this.crud.doImport()
      this.$refs.upload_import.submit()
    },
    batchUpdateSubmit(){
      const updateDto = this.batchUpdate
      if( updateDto.visitTime.length){
        updateDto.visitTime = `[${updateDto.visitTime.join(',')}]`
      }else {
        updateDto.visitTime = null
      }


      const updateIdList = this.crud.selections.map(i=>i.id)
      const data = {
        updateDto,
        updateIdList
      }
      batchUpdate(data).then(res=>{
        if (res.status === 200){
          this.$message.success(res.msg)
          this.batchUpdate={
            customerAreaId:null,
            deptId:null,
            userId:null,
            visitTime:[],
            visitLineId:null
          }
          this.showBatchUpdateDialog = false
          this.crud.refresh()
        }else {
          this.$message.error(res.msg)
        }
      })
    },
    toSyncCustomerGoods(){
      let ids = []
      const that = this
      if (this.crud.selections.length){
        for (let i in this.crud.selections){
          ids.push(this.crud.selections[i].id)
        }
        crudBasCustomer.syncCustomerGoods({ids}).then(res=>{
          if (res.status === 200){
            this.$message.success(res.msg)
          }else {
            this.$message.error(res.msg)
          }
          that.crud.loadingClose()
        }).catch(err=>{
          that.crud.loadingClose()
        })
        return
      }
      this.$confirm('未选择客户将同步所有客户会导致系统卡顿是否同步', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(res => {
        that.crud.loadingOpen()
        crudBasCustomer.syncCustomerGoods({ids}).then(res=>{
          if (res.status === 200){
            this.$message.success(res.msg)
          }else {
            this.$message.error(res.msg)
          }
          that.crud.loadingClose()
        }).catch(err=>{
          that.crud.loadingClose()
        })
      }).catch(() => {
      })
    },
    syncFCustomerGoodsToSCustomerGoods(){
      let ids = []
      const that = this
      if (this.crud.selections.length){
        for (let i in this.crud.selections){
          ids.push(this.crud.selections[i].id)
        }
        crudBasCustomer.syncFCustomerGoodsToSCustomerGoods({ids}).then(res=>{
          if (res.status === 200){
            this.$message.success(res.msg)
          }else {
            this.$message.error(res.msg)
          }
          that.crud.loadingClose()
        }).catch(err=>{
          that.crud.loadingClose()
        })
        return
      }
      this.$confirm('未选择客户将下发所有客户会导致系统卡顿是否同步', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(res => {
        that.crud.loadingOpen()
        crudBasCustomer.syncFCustomerGoodsToSCustomerGoods({ids}).then(res=>{
          if (res.status === 200){
            this.$message.success(res.msg)
          }else {
            this.$message.error(res.msg)
          }
          that.crud.loadingClose()
        }).catch(err=>{
          that.crud.loadingClose()
        })
      }).catch(() => {
      })
    },
    downloadTemplate(name) {
      request({
        url: 'api/common/downloadExcelTemplate?name=' + name,
        method: 'get',
        responseType: 'blob'
      }).then((res) => {
        const a = document.createElement('a')
        const blob = new Blob([res], {
          type: 'application/vnd.ms-excel'
        })
        const objectUrl = URL.createObjectURL(blob)
        a.setAttribute('href', objectUrl)
        a.setAttribute('download', name)
        a.click()
      })
    },
    syncSCustomerGoodsToCustomerGoods(){
      let ids = []
      const that = this
      if (this.crud.selections.length){
        for (let i in this.crud.selections){
          ids.push(this.crud.selections[i].id)
        }
        crudBasCustomer.syncSCustomerGoodsToCustomerGoods({ids}).then(res=>{
          if (res.status === 200){
            this.$message.success(res.msg)
          }else {
            this.$message.error(res.msg)
          }
          that.crud.loadingClose()
        }).catch(err=>{
          that.crud.loadingClose()
        })
        return
      }
      this.$confirm('未选择客户将下发所有客户会导致系统卡顿是否同步', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(res => {
        that.crud.loadingOpen()
        crudBasCustomer.syncSCustomerGoodsToCustomerGoods({ids}).then(res=>{
          if (res.status === 200){
            this.$message.success(res.msg)
          }else {
            this.$message.error(res.msg)
          }
          that.crud.loadingClose()
        }).catch(err=>{
          that.crud.loadingClose()
        })
      }).catch(() => {
      })
    },
    createSysUser(){
      let ids = []
      const that = this
      if (this.crud.selections.length){
        for (let i in this.crud.selections){
          ids.push(this.crud.selections[i].id)
        }
        crudBasCustomer.createSysUser(ids).then(res=>{
          if (res.status === 200){
            this.$message.success(res.msg)
          }else {
            this.$message.error(res.msg)
          }
          that.crud.loadingClose()
        }).catch(err=>{
          that.crud.loadingClose()
        })
        return
      }
    },
    toAdd() {
      this.$router.replace({
        path: 'basCustomerDetail/0',
        query: {id: 0},
        title: '新增商品档案'
      })
    },
    checkArea(data, node) {
      this.query.customerAreaId = data.id
      // this.$refs.areaTree.setCheckedNodes([node])
      this.crud.toQuery()
    },
    checkType(data, node) {
      this.query.customerTypeId = data.id
      // this.$refs.typeTree.setCheckedNodes([node])
      this.crud.toQuery()
    },
    toCopy(row) {

      let _data = JSON.parse(JSON.stringify(row))
      _data.code = this.form.code + "1"
      sessionStorage.setItem("customerForm_" + _data.code, JSON.stringify(_data));
      //打开一个新增界面
      this.$router.push({
        path: '/bas/customer/basCustomerDetail/' + _data.code,
        query: {id: _data.code},
        title: '新增用户档案'
      })

    },
  }
}
</script>

<style scoped>
.table-img {
  display: inline-block;
  text-align: center;
  background: #ccc;
  color: #fff;
  white-space: nowrap;
  position: relative;
  overflow: hidden;
  vertical-align: middle;
  width: 32px;
  height: 32px;
  line-height: 32px;
}
.imgTitle{
  font-size: 30px;
}
.hamburger {
  display: inline-block;
  vertical-align: middle;
  width: 20px;
  height: 20px;
  position: absolute;
  left:0px;
  top:20px;
}
.credit{
  cursor: pointer;
  color: blue;
  font-size: 20px;
}
</style>
